using UnityEngine;
using System.Collections;

public class LineConnector : MonoBehaviour 
{
	public static LineConnector Instance;
	
	public Material pencilMaterial;
	public int lengthOfLineRenderer = 2;
	public Camera guiCamera;
	
	public LineRenderer lineRenderer;
	
    int point1 = 0;
	int point2 = 1;
	
	Ray ray;
	RaycastHit hit;
	
	public bool lockNode = false;
	public bool currentNode = false;
	public bool lastNode = false;
	public bool firstNode = false;
	
	Transform thisTransform;
	
	float lineWidth = 0.05f;
	float lineZ	= -1.0f;
	
	bool drawShapeCalled = false;

	void Awake ()
	{	
		thisTransform = transform;
		Instance = this;
		
		guiCamera = GameObject.FindGameObjectWithTag("GUICamera").camera;
		
		lineRenderer = gameObject.GetComponent<LineRenderer>();
		
        lineRenderer.material = pencilMaterial;
        lineRenderer.SetWidth( lineWidth , lineWidth );	
		lineRenderer.SetVertexCount(lengthOfLineRenderer);
		
		drawShapeCalled = true;
	}
	
	void Update() 
	{
		if ( drawShapeCalled )
			DrawLines ();
    }
	
	public void LineRendererProperties ()
	{
		lengthOfLineRenderer = 2;
	}
	
	void DrawLines ()
	{
		
//		if ( drawShapeCalled )
//		{
//			drawShapeCalled = false;
//			LineProperties ();
//		}
		
		if ( currentNode && !lockNode )
		{
			lineRenderer = GetComponent<LineRenderer>();
	        Vector3 pos1 = new Vector3(this.transform.position.x, this.transform.position.y, lineZ);
	        lineRenderer.SetPosition( point1, pos1);
			
	        ray = guiCamera.ScreenPointToRay( Input.mousePosition );
			
	        if ( Physics.Raycast( ray, out hit ))
			{
				if ( !lockNode )
				{
					if ( hit.collider.tag == "Node" && hit.collider.transform != thisTransform && hit.collider.GetComponent<LineConnector>().lastNode == false)
					{
						Vector3 pos2 = new Vector3 ( hit.collider.transform.position.x, hit.collider.transform.position.y, lineZ );
						lineRenderer.SetPosition( point2, pos2 );
						
						lockNode = true;
						hit.collider.GetComponent<LineConnector>().currentNode = true;
						hit.collider.GetComponent<LineConnector>().lastNode = true;
						
						QuestionList.Instance.nodeIndex += 1;
						QuestionList.Instance.nodeCount[QuestionList.Instance.nodeIndex] = true;					
						Debug.Log(QuestionList.Instance.nodeIndex + " " + QuestionList.Instance.nodeCount[QuestionList.Instance.nodeIndex]);

						if ( hit.collider.GetComponent<LineConnector>().firstNode == true && hit.collider.GetComponent<LineConnector>().lastNode == true )
						{
							QuestionManager.Instance.completedShape = true;
						}
					}
					else
					{
						Vector3 pos2 = new Vector3 ( hit.point.x, hit.point.y, lineZ );
						lineRenderer.SetPosition( point2, pos2 );
					}	
				}		
			}
		}
	}
	
}
